<template>
    <div class="home">
        <div id="container-demo3" class="container-demo3"></div>
    </div>
</template>

<script>
import { createChart, CrosshairMode } from "lightweight-charts";
import moment from 'moment';
export default {
    data() {
        return {
            chart: null,
            candleSeries: null,
            volumeSeries: null
        };
    },
    mounted() {
        const container = document.getElementById('container-demo3');
        this.chart = createChart(container, {
            width: container.clientWidth,
            height: container.clientHeight,
            layout: {
                textColor: 'white',
                background: { type: 'solid', color: '#253248' },
            },
            AreaStyle: {
                invertFilledArea: false
            },
            crosshair: {
                mode: CrosshairMode.Normal
            },
            priceScale: {
                borderColor: "#485c7b"
            },
            timeScale: {
                borderColor: "#485158"
            },
            watermark: {
                text: "老板",
                fontSize: 256,
                color: "rgba(256, 256, 256, 0.1)",
                visible: false
            },
            grid: {
                vertLines: {
                    color: "#334158"
                },
                horzLines: {
                    color: "#334158"
                }
            }
        });

        // 添加工具提示
        const toolTipWidth = 180;
        const toolTipHeight = 70;
        const toolTipMargin = 15;

        const toolTip = document.createElement('div');
        toolTip.style = `width: ${toolTipWidth}px; height:${toolTipHeight}px; position: absolute; display: none; padding: 15px; box-sizing: border-box; font-size: 12px; text-align: left; z-index: 1000; top: 12px; left: 12px; pointer-events: none; border: 1px solid; border-radius: 2px;font-family: -apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;`;
        toolTip.style.background = 'black';
        toolTip.style.color = 'white';
        toolTip.style.borderColor = 'rgba( 38, 166, 154, 1)';
        container.appendChild(toolTip);

        // 添加十字光标
        this.chart.subscribeCrosshairMove(param => {
            if (
                param.point === undefined ||
                !param.time ||
                param.point.x < 0 ||
                param.point.x > container.clientWidth ||
                param.point.y < 0 ||
                param.point.y > container.clientHeight
            ) {
                toolTip.style.display = 'none';
            } else {
                console.log('鼠标参数', param);
                toolTip.style.display = 'block';
                const data = param.seriesData.get(this.candleSeries);
                const volume = param.seriesData.get(this.volumeSeries);
                console.log('volume', volume);
                console.log('param.seriesData', param.seriesData);
                const price = data?.value !== undefined ? data?.value : data?.close;
                toolTip.innerHTML = `
                <div style="padding:5px 10px !important;">
                    <div style="font-size: 24px; margin: 4px 0px; color: ${'white'}">
                    price: ${Math.round(100 * price) / 100}
                    </div>

                    <div style="color: ${'white'}">
                        volume: ${Math.round(100 * volume.value) / 100}
                    </div>
                    <div style="color: ${'white'}">
                            ${param.time.year}/${param.time.month}/${param.time.day}
                    </div>
                </div>
           `;

                const y = param.point.y + container.offsetTop;
                let left = param.point.x + container.offsetLeft + toolTipMargin;
                if (left > container.clientWidth - toolTipWidth) {
                    left = param.point.x + container.offsetLeft - toolTipMargin - toolTipWidth;
                }

                let top = y + toolTipMargin;
                if (top > container.clientHeight - toolTipHeight) {
                    top = y - toolTipHeight - toolTipMargin;
                }
                toolTip.style.left = left + 'px';
                toolTip.style.top = top + 'px';
            }
            // 设置图表的区间
            this.chart.timeScale().fitContent()
        });

        this.candleSeries = this.chart.addCandlestickSeries({
            upColor: "#4bffb5",
            downColor: "#ff4976",
            borderDownColor: "#ff4976",
            borderUpColor: "#4bffb5",
            wickDownColor: "#838ca1",
            wickUpColor: "#838ca1"
        });

        this.volumeSeries = this.chart.addHistogramSeries({
            color: "#385263",
            lineWidth: 2,
            priceFormat: {
                type: "volume"
            },
            overlay: true,
            scaleMargins: {
                top: 0.7,
                bottom: 0
            }
        });

        for (let i = 0; i < 150; i++) {
            const bar = this.nextBar();
            this.candleSeries.update(bar);
            this.volumeSeries.update(bar);
        }

        this.resize();

        setInterval(() => {
            const bar = this.nextBar();
            this.candleSeries.update(bar);
            this.volumeSeries.update(bar);
        }, 3000);

        window.addEventListener("resize", this.resize, false);
    },
    methods: {
        resize() {
            const container = document.getElementById('container-demo3');
            this.chart.applyOptions({ width: container.clientWidth, height: container.clientHeight });

            setTimeout(() => this.chart.timeScale().fitContent(), 0);
        },
        nextBar() {
            if (!this.nextBar.date) this.nextBar.date = new Date(2020, 0, 0);
            if (!this.nextBar.bar) this.nextBar.bar = { open: 300, high: 360, low: 220, close: 340 };
            console.log('this.nextBar.date', this.nextBar.date);
            this.nextBar.date.setDate(this.nextBar.date.getDate() + 1);
            this.nextBar.bar.time = {
                year: this.nextBar.date.getFullYear(),
                month: this.nextBar.date.getMonth() + 1,
                day: this.nextBar.date.getDate()
            };

            let old_price = this.nextBar.bar.close;
            let volatility = 0.1;
            let rnd = Math.random();
            let change_percent = 2 * volatility * rnd;

            if (change_percent > volatility) change_percent -= 2 * volatility;

            let change_amount = old_price * change_percent;
            this.nextBar.bar.open = this.nextBar.bar.close;
            this.nextBar.bar.close = old_price + change_amount;
            this.nextBar.bar.high =
                Math.max(this.nextBar.bar.open, this.nextBar.bar.close) +
                Math.abs(change_amount) * Math.random();
            this.nextBar.bar.low =
                Math.min(this.nextBar.bar.open, this.nextBar.bar.close) -
                Math.abs(change_amount) * Math.random();
            this.nextBar.bar.value = Math.random() * 100;
            this.nextBar.bar.color =
                this.nextBar.bar.close < this.nextBar.bar.open
                    ? "rgba(255, 128, 159,1)"
                    : "rgba(107, 255, 193, 1)";

            return this.nextBar.bar;
        }
    }
}
</script>

<style lang="scss" scoped>
.home {
    width: 100%;
    height: 100%;

    #container-demo3 {
        width: 100%;
        border: 1px solid red;
        height: 600px;
        background-color: #253248;
    }
}

::v-deep #tv-attr-logo {
    display: none;
}
</style>
